<?php


namespace app\index\model;


use app\index\common\Common;
use think\Db;
use think\Exception;
use think\Model;

class CustomerOrder extends Model
{
    /**
     * 获取每月销售额
     * create by yhb on 2021/3/17 13:33
     * @param $search_param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSellingPrice($search_param)
    {
        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('report_sell');

        $where['co.del_flag'] = ['=', 0];
        if(!empty($search_user)){
            $where['co.create_user'] = ['in', $search_user];
        }else if($search_param['user']){
            $where['co.create_user'] =  ['=', $search_param['user']];
        }
        if(!empty($search_param['date'])){
            $month = substr($search_param['date'],0,7);
        }else{
            $month = date('Y-m',time());
        }

        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['co.create_group'] = ['=', $search_param['group_id']];
        }

        $customerOrderClass = new self();

        $semRes = $customerOrderClass
            ->alias('co')
            ->field('date_format(co.create_time,\'%Y-%m-%d\') days,sum(co.selling_price) sell')
            ->join('user u', 'co.create_user = u.id','left')
            ->whereRaw('date_format(co.create_time,\'%Y-%m\') = '."'$month'")
            ->where($where)
            ->group('days')
            ->select()
            ->toArray();
        // x 轴数据，作为 x 轴标注
        if(!empty($search_param['date'])){
            $j = date('t',strtotime($search_param['date']));
            $start_time = strtotime($search_param['date']);
        }else{
            $j = date("t"); //获取当前月份天数
            $start_time = strtotime(date('Y-m-01'));  //获取本月第一天时间戳
        }
        $xData = array();
        for($i=0;$i<$j;$i++)
        {
            $xData[] = date('Y-m-d',$start_time+$i*86400); //每隔一天赋值给数组
        }
        $semRes_list=[];
        foreach ($semRes as $kk=>$vv)
        {
            $semRes_list[$vv['days']] = round($vv['sell'],2);
        }
        //处理获取到的数据
        $ySemData = array();
        $monthDay = [];
        if(!empty($semRes))
        {
            foreach ($xData as $k=>$v)
            {
                $monthDay[] = substr($v, 8);
                if (isset($semRes_list[$v])) {
                    $ySemData[$k] = round($semRes_list[$v], 2);
                } else {
                    $ySemData[$k] = 0;
                }
            }
        }else{
            foreach ($xData as $k=>$v)
            {
                $monthDay[] = substr($v,8);
                $ySemData[$k] = 0;
            }
        }

        $data_list['monthDay'] = $monthDay;
        $data_list['ySemData'] = $ySemData;
        return ['status'=>true,'result'=>['data_list'=>$data_list,'action_role'=>$action_role]];
    }

    public static function getCustomerList($search_param){
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass = new CustomerOrderDetail();
        $where['co.del_flag']=['=',0];

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');

        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['co.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['co.create_user'] = ['in', $search_user];
        }else if(is_numeric($search_param['create_user'])){
            $search_user=[$search_param['create_user']];
            $where['co.create_user'] = ['in', $search_user];
        }
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            $where[$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];

        }

        if (is_numeric($search_param['status'])) {
            $where['co.status']=['=',$search_param['status']];
        }
        $obj=$CustomerOrderClass
            ->alias('co')
            ->join('__CUSTOMER__ ct','co.customer_name=ct.id','left')
            ->where($where)
            ->field('ct.nick_name name,ct.id,ct.email,date_format(ct.create_time,\'%Y-%m-%d\') create_time')
            ->group('co.customer_name')
            ->select();
        $data=$obj->toArray();
        foreach ($data as $key=>$value){
            if(!$value['email'] && round((strtotime(date('Y-m-d'))-strtotime($value['create_time']))/3600/24,2)>2){
                $data[$key]['red']=true;
            }else{
                $data[$key]['red']=false;
            }
        }
        return $data;
    }

    public static function getList($search_param,$page_param): array
    {
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass = new CustomerOrderDetail();
        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole(['order','customer_order_edit']);

        //如果权限返回组为null则以前端传递的组为条件
        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['co.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['co.create_user'] = ['in', $search_user];
        }else if(is_numeric($search_param['create_user'])){
            $search_user=[$search_param['create_user']];
            $where['co.create_user'] = ['in', $search_user];
        }

        $where['co.del_flag']=['=',0];
        if (is_numeric($search_param['customer_name'])) {
            $where['co.customer_name']=['=',$search_param['customer_name']];
        }
        if (is_numeric($search_param['status'])) {
            $where['co.status']=['=',$search_param['status']];
        }
        if (is_numeric($search_param['selling_price'])) {
            $where['co.selling_price']=['=',$search_param['selling_price']];
        }
        if (!empty($search_param['create_time'])) {
            $where['co.create_time']=['between',[$search_param['create_time'].' 00:00:00',$search_param['create_time'].' 23:59:59']];
        }
        $namesWhere=[];
        if (!empty($search_param['search_key']) && !empty($search_param['search_value'])) {
            $namesWhere[$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];
            $detailWhere[$search_param['search_key']]=['like','%'.$search_param['search_value'].'%'];
            $detail_id=$CustomerOrderDetailClass->where($detailWhere)->where('del_flag',0)->column('customer_order_id');
            $id=$CustomerOrderClass
                ->alias('co')
                ->join('__CUSTOMER__ ct','co.customer_name=ct.id','left')
                ->join('__USER__ u','co.create_user=u.id','left')
                ->where($where)->where($namesWhere)->column('co.id');
            if (empty($id)&&empty($detail_id)){
                return ['status'=>true,'result'=>['order'=>[],'total'=>0,'action_role'=>$action_role]];
            }
            $ids=array_merge($detail_id,$id);
            $where['co.id']=['in', $ids];
        }
        $obj=$CustomerOrderClass
            ->alias('co')
            ->join('__CUSTOMER__ ct','co.customer_name=ct.id','left')
            ->join('__USER__ u','co.create_user=u.id','left')
            ->where($where)
            ->field('co.id,co.pro_id,co.customer_name,co.status,co.cn_name,co.en_name,co.pro_type,co.amount,co.weight,co.selling_price,ct.nick_name,co.create_time,co.create_user,co.create_group,u.user_name')
            ->paginate($page_param['page_size'],false,['page'=>$page_param['page_num']]);

        if($obj->isEmpty()){
            return ['status'=>true,'result'=>['order'=>[],'total'=>0,'action_role'=>$action_role]];
        }
        $count=$obj->total();
        $data=$obj->items();
        foreach($data as $key=>$value){
            $data[$key]['type_text']=Product::$product_type[$value['pro_type']];
            $data[$key]['price'] =  $value['selling_price'];
            $data[$key]['curr']='USD';
            //$data[$key]['create_time']=explode(' ',$value['create_time'])[0];
        }
        return ['status'=>true,'result'=>['order'=>$data,'total'=>$count,'action_role'=>$action_role]];
    }

    public static function createOrder($data,$pack_product,$pro_id): array
    {
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        $ProductClass = new Product();

        $CustomerOrderClass->startTrans();
        try {
            $customer_id=Customer::checkCustomer($data['customer_name'],$data['create_group']);

            $data['customer_name']=$customer_id;
            #查询库存数据 增加行锁
            $stock_list=$ProductClass->where('id','in',$pro_id)->where('del_flag',0)->lock(true)->column('amount,demand_stock,locked_demand_stock,type','id');
            /*if(empty($stock_list)){
                throw Exception('商品库存未找到');
            }*/

            if(empty($pack_product) && !empty($stock_list)) {
                $arr=&$stock_list[$data['pro_id']];
                ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=Common::demandStock($arr,$data['amount']);
                $data['demand_stock']=$demand_stock;
                $arr['demand_stock']=$stock_demand_stock;
                $arr['locked_demand_stock'] = $stock_locked_demand_stock;
            }
            $CustomerOrderClass->data($data);
            $result = $CustomerOrderClass->save();
            if ($result === false) {
                throw Exception('保存订单失败');
            }
            $customer_order_id=$CustomerOrderClass->id;
            if(!empty($pack_product)){
                foreach ($pack_product as $key=>$value){
                    $arr=&$stock_list[$value['pro_id']];
                    ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=Common::demandStock($arr,$value['amount']);
                    $pack_product[$key]['demand_stock']=$demand_stock;
                    $arr['demand_stock']=$stock_demand_stock;
                    $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                    $pack_product[$key]['customer_order_id']=$customer_order_id;
                }
//                $CustomerOrderDetailClass->data($pack_product);
                $result=$CustomerOrderDetailClass->insertAll($pack_product);
                if($result===false) {
                    throw Exception('保存订单商品详情失败');
                }
            }
            if(!empty($stock_list)) {
                $result = $ProductClass->allowField(['id','demand_stock','locked_demand_stock'])->isUpdate(true)->saveAll($stock_list);
                if($result===false){
                    throw Exception('保存库存失败');
                }
            }

            $CustomerOrderClass->commit();
            return ['status' => true, 'result' => '下单成功'];
        } catch (\Exception $e) {
            $CustomerOrderClass->rollback();
            trace($e->getMessage(), 'error');
            return ['status' => false, 'result' => '下单失败.' . $e->getMessage()];
        }
    }

    public static function updateOrder($id,$data,$pack_product,$pro_id): array
    {
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        $ProductClass=new Product();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');

        $CustomerOrderClass->startTrans();
        try {
            if(!empty($search_user)){
                $where['create_user']=['in',$search_user];
            }
            if(!empty($group)){
                $where['create_group']=['=',$group];
            }
            $where['id']=['=',$id];
            $where['del_flag']=['=',0];
            $where['status']=['=',0];
            $old_customer_order=$CustomerOrderClass->where($where)->lock(true)->field('id,create_group,amount,demand_stock,pro_id')->find();
            if(empty($old_customer_order)){
                throw Exception('未找到订单');
            }
            $old_customer_order_detail=$CustomerOrderDetailClass->where('customer_order_id',$id)->where('del_flag',0)->group('pro_id')->lock(true)->column('sum(amount) amount,sum(demand_stock) demand_stock','pro_id');
            $old_pro_id=array_keys($old_customer_order_detail);
            $pro_id=array_unique(array_merge($pro_id,$old_pro_id));

            $stock=$ProductClass->where('id','in',$pro_id)->lock(true)->where('del_flag',0)->field('id,amount,demand_stock,locked_demand_stock,type')->select()->toArray();
            /*if(empty($stock)){
                throw Exception('未找到库存');
            }*/
            $stock_list=[];
            foreach ($stock as $key=>$value){
                if($value['type']===1) {
                    if ($value['id'] === $old_customer_order['pro_id']) {
                        $value['demand_stock'] -= $old_customer_order['amount'];
                        $value['locked_demand_stock'] -= $old_customer_order['demand_stock'];
                    } elseif (isset($old_customer_order_detail[$value['id']])) {
                        $value['demand_stock'] -= $old_customer_order_detail[$value['id']]['amount'];
                        $value['locked_demand_stock'] -= $old_customer_order_detail[$value['id']]['demand_stock'];
                    }
                }
                $stock_list[$value['id']]=$value;
            }
            $delete_pack=[];
            $update_pack=[];
            $insert_pack=[];
            if(!empty($pack_product)) {
                foreach ($pack_product as $key => $value) {
                    $arr=&$stock_list[$value['pro_id']];
                    if ($value['delete'] && $value['id']) {
                        unset($value['delete']);
                        $delete_pack[] = $value['id'];
                        continue;
                    }
                    if (!$value['delete'] && $value['id']) {
                        unset($value['delete']);
                        ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=Common::demandStock($arr,$value['amount']);
                        $value['demand_stock']=$demand_stock;
                        $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                        $arr['demand_stock']=$stock_demand_stock;
                        $update_pack[] = $value;
                        continue;
                    }
                    if (!$value['id'] && $value['delete'] === false) {
                        unset($value['delete']);
                        ['demand_stock'=>$demand_stock,'stock_demand_stock'=>$stock_demand_stock,'stock_locked_demand_stock'=>$stock_locked_demand_stock]=Common::demandStock($arr,$value['amount']);
                        $value['demand_stock']=$demand_stock;
                        $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                        $arr['demand_stock']=$stock_demand_stock;
                        $insert_pack[] = $value;
                        continue;
                    }
                }
            }else{
                if($data['pro_id']) {
                    $arr =& $stock_list[$data['pro_id']];
                    ['demand_stock' => $demand_stock, 'stock_demand_stock' => $stock_demand_stock, 'stock_locked_demand_stock' => $stock_locked_demand_stock] = Common::demandStock($arr, $data['amount']);
                    $data['demand_stock'] = $demand_stock;
                    $arr['locked_demand_stock'] = $stock_locked_demand_stock;
                    $arr['demand_stock'] = $stock_demand_stock;
                }
            }

            $customer_id=Customer::checkCustomer($data['customer_name'],$old_customer_order['create_group']);
            $data['customer_name']=$customer_id;
            $result = $CustomerOrderClass->save($data,['id'=>$id]);
            if ($result === false) {
                throw Exception('更新失败');
            }

            if (!empty($insert_pack)) {
                $result = $CustomerOrderDetailClass->insertAll($insert_pack);
                if ($result === false) {
                    throw Exception('修改失败 ' . '添加失败');
                }
            }
            if (!empty($update_pack)) {
                $result = $CustomerOrderDetailClass->isUpdate(true)->saveAll($update_pack);
                if ($result === false) {
                    throw Exception('修改失败 ' . '更新失败');
                }
            }
            if (!empty($delete_pack)) {
                $result = $CustomerOrderDetailClass->isUpdate(true)->where('id', 'in', $delete_pack)->update(['del_flag' => 1]);
                if ($result === false) {
                    throw Exception('修改失败 ' . '删除失败');
                }
            }
            $result=$ProductClass->allowField(['id','demand_stock','locked_demand_stock'])->isUpdate(true)->saveAll($stock_list);
            if($result===false){
                throw Exception('更新库存失败');
            }

            $CustomerOrderClass->commit();
            return ['status' => true, 'result' => '更新成功'];
        } catch (\Exception $e) {
            $CustomerOrderClass->rollback();
            trace($e->getMessage(), 'error');
            return ['status' => false, 'result' => '更新失败' . $e->getMessage()];
        }
    }

    public static function cancelCustomerOrder($id){
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        $ProductClass=new Product();
        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');

        if(!empty($search_user)){
            $where['create_user']=['in',$search_user];

        }
        if(!empty($group)){
            $where['create_group']=['=',$group];
        }
        $where['id']=['=',$id];
        $where['del_flag']=['=',0];
        $where['status']=['=',0];
        $order=$CustomerOrderClass->where($where)->field('id,create_group,pro_id,demand_stock,amount')->find();
        if(empty($order)){
            return ['status'=>false,'result'=>'未找到订单'];
        }
        $customer_order_detail=$CustomerOrderDetailClass->where('customer_order_id','in',$id)->where('del_flag',0)->group('pro_id')->field('pro_id,sum(amount) amount,sum(demand_stock) demand_stock,type')->select()->toArray();
        try {
            $pro_id=[];
            $stock_restore=[];
            if($order['pro_id']!==0){
                $pro_id=[$order['pro_id']];
                if($order['demand_stock']>0) {
                    $stock_restore[$order['pro_id']]['locked_demand_stock'] = $order['demand_stock'];
                }
                $stock_restore[$order['pro_id']]['demand_stock']=$order['amount'];
            }
            if(!empty($customer_order_detail)){
                foreach ($customer_order_detail as $key=>$value){
                    if($value['type']===1) {
                        $stock_restore[$value['pro_id']]['demand_stock'] = $value['amount'];
                        $pro_id[] = $value['pro_id'];
                        if ($value['demand_stock'] > 0) {
                            $stock_restore[$value['pro_id']]['locked_demand_stock'] = $value['demand_stock'];
                        }
                    }
                }
            }
            if(!empty($pro_id)) {
                $stock_list = $ProductClass->where('id', 'in', $pro_id)->where('del_flag', 0)->lock(true)->field('demand_stock,locked_demand_stock,id')->select()->toArray();
                if (empty($stock_list)) {
                    throw Exception('商品库存未找到');
                }
                foreach ($stock_list as $key => $value) {
                    if (isset($stock_restore[$value['id']])) {
                        $stock_list[$key]['demand_stock'] -= $stock_restore[$value['id']]['demand_stock'];
                        if(isset($stock_restore[$value['id']]['locked_demand_stock'])) {
                            $stock_list[$key]['locked_demand_stock'] -= $stock_restore[$value['id']]['locked_demand_stock'];
                        }
                    }
                }
                $result = $ProductClass->isUpdate(true)->saveAll($stock_list);

                if($result===false){
                    throw Exception('商品库存回退失败');
                }
            }

            $result = $CustomerOrderClass->isUpdate()->save(['del_flag'=>1,'demand_stock'=>0],['id'=>$id]);
            if ($result === false) {
                throw Exception('取消失败');
            }

            $CustomerOrderDetailClass->isUpdate()->save(['del_flag'=>1,'demand_stock'=>0],['customer_order_id'=>$id]);

            $CustomerOrderClass->commit();
        } catch (\Exception $e) {
            $CustomerOrderClass->rollback();
            trace($e->getMessage(), 'error');
            return ['status' => false, 'result' => '取消失败' . $e->getMessage()];
        }
        ['status'=>$status,'result'=>$result]=Product::demandStockByProduct($pro_id);
        if($status===false){
            return ['status'=>false,'result'=>'取消成功，锁定需求库存失败',$result];
        }
        return ['status' => true, 'result' => '取消成功'];
    }

    public static function getCustomerOrderByIds($ids): array
    {
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass=new CustomerOrderDetail();
        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('order');

        if(!empty($search_user)){
            $where['co.create_user']=['in',$search_user];
        }
        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }
        $where['co.id']=['in',$ids];
        $where['co.status']=['=',0];
        $where['co.del_flag']=['=',0];

        $data=$CustomerOrderClass
            ->alias('co')
            ->where($where)
            ->join('__PRODUCT__ p','co.pro_id=p.id','left')
            ->join('__CUSTOMER__ c','co.customer_name=c.id','left')
            ->field('co.id,co.pro_id,co.pro_type,co.amount,co.weight,co.selling_price,co.create_user,IFNULL(p.pur_price,0) pur_price,co.cn_name,co.en_name,c.id customer_id,c.customer_name,c.email,c.country,c.city,c.address,c.zip_code,c.phone,co.demand_stock,co.create_group,co.create_user,co.remark,co.gift,c.ship_fee ship_fee_check')
            ->select()
            ->toArray();
        if(empty($data)){
            return ['status'=>false,'result'=>'未找到订单'];
        }
        $detail_list=[];

        $detail_data = $CustomerOrderDetailClass->alias('cod')->join('__PRODUCT__ p', 'cod.pro_id=p.id', 'left')->where('cod.customer_order_id', 'in', $ids)->where('cod.del_flag', 0)->field('cod.customer_order_id,cod.pro_id,cod.en_name,cod.cn_name,cod.amount,cod.type,cod.weight,cod.demand_stock,p.pur_price,cod.remark')->select()->toArray();
        if (!empty($detail_data)) {
            foreach ($detail_data as $value) {
                $key=$value['customer_order_id'];
                unset($value['customer_order_id']);
                $detail_list[$key][] = $value;
            }
        }
        return ['status'=>true,'result'=>['data'=>$data,'detail'=>$detail_list]];

    }

    public static function getCustomerOrderById($id): array
    {
        $CustomerOrderClass = new self();
        $CustomerOrderDetailClass=new CustomerOrderDetail();

        ['search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('customer_order_edit');

        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }

        if(!empty($search_user)){
            $where['co.create_user']=['in',$search_user];
        }

        $where['co.id']=['=',$id];
        $where['co.status']=['=',0];
        $where['co.del_flag']=['=',0];

        $data=$CustomerOrderClass
            ->alias('co')
            ->where($where)
            ->join('__PRODUCT__ p','co.pro_id=p.id','left')
            ->join('__CUSTOMER__ c','co.customer_name=c.id','left')
            ->field('co.id,co.pro_id,co.pro_type,co.amount,co.weight,co.selling_price,IFNULL(p.selling_price,0) price,co.cn_name,co.en_name,c.nick_name customer_name,co.gift, co.remark,co.create_group `group`')
            ->find();
        if(empty($data)){
            return ['status'=>false,'result'=>'未找到订单'];
        }

        $customer_order_detail=$CustomerOrderDetailClass->where('customer_order_id',$id)->where('del_flag',0)->field('id customer_order_detail_id,pro_id id,pro_id,en_name,cn_name,amount,type,weight,remark')->select()->toArray();
        if(!empty($customer_order_detail)) {
            foreach ($customer_order_detail as $key => $value) {
                $customer_order_detail[$key]['detailKeys'] = $key;
                $customer_order_detail[$key]['delete'] = false;
            }
        }
        return ['status'=>true,'result'=>['data'=>$data,'detail'=>$customer_order_detail]];
    }

    /**
     * getCustomerOrderSales
     * 获取销售额
     * @url
     * @method
     * @param array $search_param 搜索条件
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/14
     */
    public static function getCustomerOrderSales($search_param): array
    {
        $OrderCustomer=new self();

        ['action_role'=>$action_role,'search_user'=>$search_user,'group'=>$group]=ActionRole::checkUserActionRole('report_sales');
        if(!empty($group)){
            $where['co.create_group']=['=',$group];
        }else if (is_numeric($search_param['group_id']) && $search_param['group_id']) {
            $where['co.create_group'] = ['=', $search_param['group_id']];
        }

        if(!empty($search_user)) {
            $where['co.create_user'] = ['in', $search_user];
        }else if(is_array($search_param['user']) && !empty($search_param['user'])){
            $search_user=$search_param['user'];
            $where['co.create_user'] = ['in', $search_user];
        }

        $where['co.del_flag']=['=',0];
        if (!empty($search_param['create_time'])) {
            $where['co.create_time']=['between',[$search_param['create_time'][0].' 00:00:00',$search_param['create_time'][1].' 23:59:59']];
        }
        $obj=$OrderCustomer->alias('co')
            ->where($where)
            ->sum('selling_price');
        if(is_null($obj)){
            $total_sales=0;
        }else{
            $total_sales=$obj;
        }

        $obj=$OrderCustomer
            ->where($where)->alias('co')
            ->join('__USER__ u','co.create_user=u.id','left')
            ->field('round(sum(selling_price),2) price,u.user_name user,co.create_user')
            ->group('co.create_user')
            ->order('price','desc')
            ->select();
        if($obj->isEmpty()){
            $sales_data=[];
        }else{
            $sales_data=$obj->toArray();
        }

        return ['status'=>true,'result'=>['total_sales'=>$total_sales,'sales_data'=>$sales_data,'action_role'=>$action_role]];
    }
    public static function changeCustomer($ids,$name)
    {
        $orderCustomerClass=new self();
        $customerClass=new Customer();
        $rows=$orderCustomerClass->where('id','in',$ids)->column('create_group');
        $data=array_unique($rows);
        if (count($data)>1){
            return ['status'=>false,'result'=>'不同组的商品不能批量修改'];
        }
        $row=$customerClass->where(['nick_name'=>$name,'del_flag'=>0])->find();
        $id=$row['id'];
        if (!$row){
            $id=$customerClass->insertGetId(['nick_name'=>$name,'customer_name'=>$name,'country'=>2,'create_group'=>$data[0],'create_user'=>session('Login_user')['id']]);
            if ($id===false){
                return ['status'=>false,'result'=>'新客户名插入失败'];
            }
        }
        $result=$orderCustomerClass->where('id','in',$ids)->update(['customer_name'=>$id]);
        if ($result===false){
            return ['status'=>false,'result'=>'修改失败'];
        }
        return ['status'=>true,'result'=>'修改成功'];
    }
}